﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm.TransferValue
{
    public partial class FrmMain : Form
    {

        public FrmMain()
        {
            InitializeComponent();
        }

        private void btnOpenChildren_Click(object sender, EventArgs e)
        {
            FrmChildren frm = new FrmChildren();
            frm.Owner = this; // 将frm的父窗体设置为当前窗体(FrmMain)
            frm.Message = string.IsNullOrWhiteSpace(this.txtParent.Text) ? "我给子窗体传递了值" : this.txtParent.Text;
            frm.CustomChildrenTransferParentEvent += Frm_CustomChildrenTransferParentEvent; // 子窗体事件父窗体实现(事件委托)
            frm.Show();
        }

        // 子窗体事件父窗体实现(事件委托)
        private void Frm_CustomChildrenTransferParentEvent(DataEventArgs data)
        {
            this.txtChildren.Text = data.Data;
        }

        #region 系统封装的事件使用案例

        public event EventHandler<DataEventArgs> DataTransfer;
        private void btnTransfer_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.txtParent.Text))
            {
                MessageBox.Show("请输入Parent值", "提示");
                return;
            }
            DataTransfer.Invoke(this, new DataEventArgs(this.txtParent.Text));
        }

        #endregion

        #region 自定义事件使用案例

        public delegate void CustomParentTransferChildrenDelegate<in T>(object sender, T e);
        public event CustomParentTransferChildrenDelegate<DataEventArgs> CustomParentTransferChildrenEvent;

        private void btnCustom_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.txtParent.Text))
            {
                MessageBox.Show("请输入Parent值", "提示");
                return;
            }
            CustomParentTransferChildrenEvent.Invoke(this, new DataEventArgs(this.txtParent.Text));
        }
        #endregion


        #region 子传父方法

        public void SetChildrenText(string input)
        {
            this.txtChildren.Text = input;
        }

        #endregion

    }
}
